package com.hundsun.fcp.webplugin.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;

import android.content.Context;

import com.hundsun.fcp.common.logger.AndroidLogger;
import com.hundsun.fcp.common.logger.Logger;
import com.hundsun.fcp.webplugin.WebPluginConfig;

public class AssetsUtil {
	private static final Logger LOGGER = AndroidLogger.getLogger() ;
	public static final String ANDROID_BUNDLE_FILE_NAME = "android_bundle.zip";
	private static final int BUFFER_SIZE = 8*1024;
	
	public static void clearSDCardAsset() {
		try {
			String str = WebPluginConfig.getBaseDir();
			deleteFile(new File(str));
		} catch (Exception e) {
			LOGGER.error("清除sdcard 文件", e);
		}
	}

	public static void clearWebPluginAsset() {
		try {
			String str = WebPluginConfig.getWebPluginDir();
			deleteFile(new File(str));
		} catch (Exception e) {
			LOGGER.error("清除sdcard 文件", e);
		}
	}
	 
	 
	 public static void copyAssetsBundleToSDCard(Context pContext, String pFilePath) throws Exception {
		 String _sdPath = WebPluginConfig.getWebPluginDir();  
		 ZipUtil.unZip(pContext, ANDROID_BUNDLE_FILE_NAME, _sdPath) ;
	 }
	 
	 public static void copyAssetsToSDCard(Context pContext) throws Exception{
		 if(!FileUtil.isFolderExisted(WebPluginConfig.getWebPluginDir())){
			 FileUtil.makeDirectories(WebPluginConfig.getWebPluginDir()) ;
		 }else{
			 clearWebPluginAsset() ;
		 }
		 String zipPath = SdCardUtil.ProtocolAndroidAsset ;
		 copyAssetsBundleToSDCard(pContext, zipPath) ;
	 }
	 
	 
	 
	 private static void deleteFile(File pFile)
	  {
	    if (pFile.exists())
	    {
	    	if(pFile.isDirectory()){
	    		File[] _files = pFile.listFiles();
	    		 for (int i = 0; i < _files.length; i++) {
	    			 deleteFile(_files[i]);
	    		 }
	    		 pFile.delete() ;
	    		 
	    	}else{
	    		pFile.delete();
	    	}
	    	
	    }
	  }
	 
	 public static String readWebPluginManifest(String fileName){
		 try {
			return FileUtil.getInputStream(new FileReader(fileName)) ;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		 return null ;
	 }
	 
	 
	 public static String readAssetsFile(Context pContext,String fileName){
		 try { 
             return FileUtil.getInputStream(new InputStreamReader(pContext.getResources().getAssets().open(fileName))) ;
		} catch (IOException e) {
			e.printStackTrace();
		}
		 
		 return null ;
	 }
	 
	 
}
